package com.rskj.cashbook.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.service.iml.CashBookService;
import com.rskj.cashbook.vo.BillTypeDTO;
import com.rskj.cashbook.vo.CashBook;
import com.rskj.cashbook.vo.Query.QueryBase;
import com.rskj.cashbook.vo.Query.StatementsQueryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("cash/book")
@RequiredArgsConstructor
@ResponseBody
public class CashBookController {
    private final CashBookService cashBookService;

    @PostMapping("save")
    public ResponseEntity<Integer> insert(@RequestBody CashBook cashBook) {
        // 设置默认账单类型
        if (cashBook.getBillType() == null) {
            cashBook.setBillType("EXPENSE"); // 默认为支出类型
        }
        int result = cashBookService.insert(cashBook);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存入账账单（收入）
     */
    @PostMapping("save/income")
    public ResponseEntity<Integer> insertIncome(@RequestBody CashBook cashBook) {
        // 设置为收入类型
        cashBook.setBillType("INCOME");
        cashBook.setBillCategory("INCOME");
        cashBook.setIsIncome(1);
        
        int result = cashBookService.insert(cashBook);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存出账账单（支出）
     */
    @PostMapping("save/expense")
    public ResponseEntity<Integer> insertExpense(@RequestBody CashBook cashBook) {
        // 设置为支出类型
        cashBook.setBillType("EXPENSE");
        cashBook.setBillCategory("EXPENSE");
        cashBook.setIsIncome(0);
        
        int result = cashBookService.insert(cashBook);
        return ResponseEntity.ok(result);
    }

    @PostMapping("update")
    public ResponseEntity<Integer> update(@RequestBody List<CashBook> cashBook) {
        int result = cashBookService.updateCashBook(cashBook);
        return ResponseEntity.ok(result);
    }

    @PostMapping("query")
    public ResponseEntity<PageInfo<CashBook>> selectCashBook(@RequestBody QueryBase<CashBook> queryCashBook) {
        PageHelper.startPage(queryCashBook.getPageNumber(), queryCashBook.getPageSize());
        PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBookGroupByDate());
        return ResponseEntity.ok(result);
    }

    @PostMapping("query/{consumerDate}")
    public ResponseEntity<PageInfo<CashBook>> selectCashBook(@PathVariable Date consumerDate) {
        PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(new CashBook().setConsumerDate(consumerDate)));
        return ResponseEntity.ok(result);
    }

    @GetMapping("details/list")
    public ResponseEntity<PageInfo<CashBook>> list(QueryBase queryBase) {
        PageHelper.startPage(queryBase.getPageNumber(), queryBase.getPageSize());
        PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(new CashBook()));
        return ResponseEntity.ok(result);
    }

    @PostMapping("query/statement")
    public ResponseEntity<BigDecimal> statements(@RequestBody StatementsQueryVo queryVo) {
        BigDecimal result = cashBookService.statements(queryVo);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据账单类型查询
     */
    @GetMapping("type/{billType}")
    public ResponseEntity getByBillType(
            @PathVariable String billType,
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            PageHelper.startPage(pageNumber, pageSize);
            CashBook query = new CashBook();
            query.setBillType(billType);
            PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.fail("根据账单类型查询失败");
        }
    }
    
    /**
     * 根据账单分类查询
     */
    @GetMapping("category/{category}")
    public ResponseEntity getByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            PageHelper.startPage(pageNumber, pageSize);
            CashBook query = new CashBook();
            query.setBillCategory(category);
            PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.fail("根据账单分类查询失败");
        }
    }

    /**
     * 查询收入账单
     */
    @GetMapping("income")
    public ResponseEntity getIncomeBills(
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            PageHelper.startPage(pageNumber, pageSize);
            CashBook query = new CashBook();
            query.setIsIncome(1);
            PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.fail("查询收入账单失败");
        }
    }

    /**
     * 查询支出账单
     */
    @GetMapping("expense")
    public ResponseEntity getExpenseBills(
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            PageHelper.startPage(pageNumber, pageSize);
            CashBook query = new CashBook();
            query.setIsIncome(0);
            PageInfo<CashBook> result = new PageInfo<>(cashBookService.selectCashBook(query));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.fail("查询支出账单失败");
        }
    }

    /**
     * 获取账单统计信息
     */
    @GetMapping("statistics")
    public ResponseEntity getBillStatistics() {
        try {
            Map<String, Object> statistics = cashBookService.getBillStatistics();
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            return ResponseEntity.fail("获取账单统计信息失败");
        }
    }
    
    /**
     * 获取账单类型统计
     */
//    @GetMapping("stats/by-type")
//    public ResponseEntity getStatsByType() {
//        try {
//            Map<String, Object> stats = cashBookService.getStatsByBillType();
//            return ResponseEntity.ok(stats);
//        } catch (Exception e) {
//            return ResponseEntity.fail("获取账单类型统计失败");
//        }
//    }
    
    /**
     * 获取账单分类统计
     */
//    @GetMapping("stats/by-category")
//    public ResponseEntity<Map<String, Object>> getStatsByCategory() {
//        try {
//            Map<String, Object> stats = cashBookService.getStatsByCategory();
//            return ResponseEntity.ok(stats);
//        } catch (Exception e) {
//            return ResponseEntity.fail("获取账单分类统计失败");
//        }
//    }
    
    /**
     * 获取所有账单类型
     */
//    @GetMapping("types")
//    public ResponseEntity<List<BillTypeDTO>> getAllBillTypes() {
//        try {
//            // 这里需要调用BillTypeController的getAllBillTypes方法
//            // 由于是同一个应用，可以直接注入BillTypeController或者创建一个Service
//            // 暂时返回空列表，等后续优化
//            return ResponseEntity.ok(List.of());
//        } catch (Exception e) {
//            return ResponseEntity.fail("获取账单类型列表失败");
//        }
//    }
    
    /**
     * 根据分类获取账单类型
     */
    @GetMapping("types/category/{category}")
    public ResponseEntity getBillTypesByCategory(@PathVariable String category) {
        try {
            // 这里需要调用BillTypeController的getBillTypesByCategory方法
            // 暂时返回空列表，等后续优化
            return ResponseEntity.ok(List.of());
        } catch (Exception e) {
            return ResponseEntity.fail("根据分类获取账单类型失败");
        }
    }
}
